<?php
namespace api\user\controller;

use api\user\model\UserLotteryModel;
use api\user\model\LotteryModel;
use api\user\model\UserModel;
use api\common\controller\RestUserBaseController;
use think\Db;

class LotteryController extends RestUserBaseController
{
    protected $UserLotteryModel;

    public function __construct()
    {
        parent::__construct();
        $this->UserLotteryModel = new UserLotteryModel();
        $this->UserModel = new UserModel();
    }


    public function index()
    {
        $param          = $this->request->param();

        $param['where'] = [
            'user_id' => $this->userId,
        ];
        $param['relation'] = 'lottery';
        $param['order'] = '-createtime';
        $data = $this->UserLotteryModel->getDatas($param);
        $lottery_intro ="抽奖说明";
        $this->success('请求成功', [
            'lottery_intro'=> $lottery_intro, 
            'list' => $data
        ]);
    }

    public function prize()
    {
        $wallet_type = $this->request->get('type');
        $LotteryModel = new LotteryModel;
        if(!empty($wallet_type)){
            $prize = $LotteryModel->where('wallet_type',$wallet_type)->select();
        }else{
            $this->error('请输入钱包类型');
        }
        $this->success('请求成功', [
            'list' => $prize
        ]);
    }

    public function save()
    {
        $param = $this->request->param();

        $result = $this->validate($param, 'Lottery');
        if ($result !== true) {
            $this->error($result);
        }
        $file = fopen("./lock.txt", "r");
        if (flock($file, LOCK_EX)) {
            // 启动事务
            Db::startTrans();
            $userInfo = Db::name('user')->where('id', $this->userId)->lock(true)->find();
            if ($param['wallet_type']) {
                //资金类型1=静态钱包,2=任务钱包,3=活动钱包
                switch ($param['wallet_type']) {
                    case '1':
                        $wallet_type = 'static_wallet';
                        $buy_type = 1;
                        $price = 10;
                        if ($userInfo['static_wallet'] < $price) {
                            $this->error('静态资产不足');
                        }
                        break;
                    case '2':
                        $wallet_type = 'mission_wallet';
                        $buy_type = 2;
                        $price = 10;
                        if ($userInfo['mission_wallet'] < $price) {
                            $this->error('任务资产不足');
                        }
                        break;
                    case '3':
                        $wallet_type = 'movable_wallet';
                        $buy_type = 3;
                        $price = 10;
                        if ($userInfo['movable_wallet'] < $price) {
                            $this->error('活动资产不足');
                        }
                        break;
                    default:
                        $this->error('参数错误');
                        break;
                }
            } else {
                $this->error('参数错误');
            }
            if (isset($buy_type)) {
                $lottery = Db::name('lottery')->where('wallet_type', $buy_type)->select();
            } else {
                $this->error('请选择抽签钱包');
            }

            $arr = [];
            if (!empty($lottery)) {
                foreach ($lottery as $key => $val) {
                    $arr[$val['id']] = $val['chance'];
                }
            }

            $lottery_id = get_rand($arr); //根据概率获取奖项id
            $prize = LotteryModel::get($lottery_id);
            $user_lottery['user_id'] = $this->userId;
            $user_lottery['lottery_id'] = $lottery_id;
            $user_lottery['createtime'] = time();
            //资金明细
            $user_balance_log['user_id'] = $this->userId;
            $user_balance_log['amount'] = $price;
            $user_balance_log['before'] = $this->user[$wallet_type];
            $user_balance_log['after'] = $this->user[$wallet_type] - $price;
            $user_balance_log['remark'] = '抽奖';
            $user_balance_log['type'] = 0;
            $user_balance_log['log_type'] = $buy_type;
            $user_balance_log['source'] = 6;
            $user_balance_log['createtime'] = time();


            try {
                Db::name('user_lottery')->insert($user_lottery);
                Db::name('user_balance_log')->insert($user_balance_log);
                Db::name('user')
                    ->where('id', $this->userId)
                    ->update([
                        $wallet_type => Db::raw($wallet_type . '-' . $price),
                    ]);
                //参与大转盘赠送58枚BTTW至任务钱包
                $user_verifytask = Db::name('user_task')
                    ->where(['task_id' => 9, 'user_id' => $this->userId])
                    ->find();
                if (!$user_verifytask) {
                    $task_reward = Db::name('task')
                        ->where(['id' => 9])
                        ->value('task_reward');
                    if ($task_reward) {
                        Db::name('user')
                            ->where(['id' => $this->userId])
                            ->update([
                                'mission_wallet' => Db::raw('mission_wallet+' . $task_reward),
                            ]);
                        $user_balance_log['user_id'] = $this->userId;
                        $user_balance_log['amount'] = $task_reward;
                        $user_balance_log['before'] = $this->user['mission_wallet'];
                        $user_balance_log['after'] = $this->user['mission_wallet'] + $task_reward;
                        $user_balance_log['remark'] = '参与大转盘';
                        $user_balance_log['type'] = 1;
                        $user_balance_log['log_type'] = 2;
                        $user_balance_log['source'] = 2;
                        $user_balance_log['task_id'] = 5;
                        $user_balance_log['createtime'] = time();
                        Db::name('user_balance_log')->insert($user_balance_log);
                        Db::name('user_task')->insert(['task_id' => 9, 'user_id' => $this->userId, 'createtime' => date('Y-m-d')]);
                    }
                }
                // 提交事务
                Db::commit();
                $this->success('抽奖成功', ['prize' => $prize]);
            } catch (\think\Exception\DbException $exception) {
                // 回滚事务
                Db::rollback();
                $this->error('抽奖失败');
            }

            flock($file, LOCK_UN);
        }
        fclose($file);
    }
}
